package com.sf.datastructure.imageUtil;

import java.io.File;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sf.module.base.BaseController;
import com.sf.module.base.BusinessException;
import com.sf.module.base.JsonResult;
import com.sf.module.common.constants.Constants;
import com.sf.module.common.constants.SysConstants;
import com.sf.module.common.util.FilesUtils;
import com.sf.module.common.util.ImageUtils;

/**
 * 移动端文件上传控制器
 * @author weiliang.mao
 *
 */
@Controller
@RequestMapping("upload")
public class UploadController extends BaseController {
	
	private static final String COMMON_MODULE = "mobile"; 
	
	/**
	 * 上传文件保存的根路径
	 */
	private String saveRootPath;
	
	private int imageCompressWidth;
	/**
	 * 上传图片
	 * @param files
	 * @param module
	 * @return
	 */
	@RequestMapping("image")
	@ResponseBody
	public JsonResult uploadImage(@RequestParam(value="file",required=false)MultipartFile[] files){
		JsonResult jsonResult = new JsonResult();
		try {
			if(files != null && files.length > 0){
				//文件保存路径
				StringBuilder path = new StringBuilder();
				path.append(COMMON_MODULE).append(Constants.UNIX_FILE_SEPARATOR).append("images")
				.append(FilesUtils.generateDirPathByTimestamp()).append(Constants.UNIX_FILE_SEPARATOR);
				
				String uploadImageFileName;
				String fullPath ;
				String[] pathResults = new String[files.length];
				for (int i =0 ; i<files.length ;i++) {
					if(files[i].getSize()<=0){
						pathResults[i] = "error:图片为空或没有内容";
						continue;
					}
					uploadImageFileName = files[i].getOriginalFilename();
					
					String fileSaveName = UUID.randomUUID().toString();
					//获取后缀名
					if (uploadImageFileName.lastIndexOf(".") >= 0) {
						fileSaveName += uploadImageFileName.substring(uploadImageFileName
								.lastIndexOf(".")).replaceAll("-", "");
					}
					fullPath = path + fileSaveName;
					//创建父目录
					File parentPath = new File(this.saveRootPath + path);
					if(!parentPath.exists()){
						parentPath.mkdirs();
					}
					File file = new File(this.saveRootPath + fullPath);
					files[i].transferTo(file);
					//压缩图片
					String absolutePath = file.getAbsolutePath();
					ImageUtils.compressPic(absolutePath, absolutePath+".thumbnail", this.imageCompressWidth);
					pathResults[i] = fullPath;
				}
				jsonResult.setData(pathResults);
			}else{
				jsonResult.setErrorMessage("上传图片失败->没有上传任何有效的图片");
			}
			
		} catch (BusinessException e) {
			jsonResult.setErrorMessage(e.getMessage());
		} catch (Exception e) {
			log.error("UploadController#uploadImage:上传图片失败", e);
			jsonResult.setErrorMessage("上传图片失败");
		}
		return jsonResult;
	}
	
	/**
	 * 获取查看附件的前缀
	 * @return
	 */
	@RequestMapping("viewPath")
	@ResponseBody
	public JsonResult attachmentViewPath(){
		JsonResult jsonResult = new JsonResult();
		try {
			jsonResult.setData(SysConstants.getAttachmentViewPath());
		} catch (BusinessException e) {
			jsonResult.setErrorMessage(e.getMessage());
		} catch (Exception e) {
			log.error("UploadController#attachmentViewPath:获取查看附件的前缀失败", e);
			jsonResult.setErrorMessage("获取查看附件的前缀失败");
		}
		return jsonResult;
	}
	
	public String getSaveRootPath() {
		return saveRootPath;
	}
	
	@Value("${ATTACHMENT_SAVE_ROOT_PATH}")
	public void setSaveRootPath(String saveRootPath) {
		this.saveRootPath = saveRootPath;
	}
	
	@Value("${IMAGE_COMPRESS_WIDTH}")
	public void setImageCompressWidth(int imageCompressWidth) {
		this.imageCompressWidth = imageCompressWidth;
	}
	

}
